package com.mallcai.bigdata.ladon.service.report.impl.handler;

import com.alicp.jetcache.Cache;
import com.alicp.jetcache.embedded.CaffeineCacheBuilder;
import com.mallcai.bigdata.ladon.service.report.impl.ReportQueryConstants;
import com.mallcai.bigdata.ladon.service.report.impl.ReportQueryContext;
import com.mallcai.bigdata.ladon.tools.MD5Util;
import com.mallcai.bigdata.ladon.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author feixy
 * @version 1.0
 * @date 2019-07-20 14:38
 */
@Slf4j
@Component
@Order(1000)
public class ParseAllParamNameHandler extends AbstractReportQueryPreHandler {

    Cache<String, Set<String>> cache = CaffeineCacheBuilder.createCaffeineCacheBuilder()
            .limit(1000)
            .expireAfterWrite(5, TimeUnit.DAYS)
            .buildCache();

    @Override
    public void preInternal(ReportQueryContext context) {
        String sql = context.getSql();
        String cacheKey = createCacheKey(sql);
        Set<String> params = cache.computeIfAbsent(cacheKey, key -> {
            log.info("未命中缓存,解析sql获取所有使用到的参数");
           return  SqlUtils.parseUniqueParamName(sql);
        });
        context.putInnerParam(ReportQueryConstants.KEY_ALL_PARAM_NAME, params);
    }


    private String createCacheKey(String sql){
        return MD5Util.getMd5(sql);
    }

}
